package accountManagementNew.controller;

import accountManagementNew.common.base.LoginVO;
import accountManagementNew.common.base.Result;
import accountManagementNew.common.dto.UserDTO;
import accountManagementNew.common.enums.ResultCodeEnum;
import accountManagementNew.common.vo.UserVO;
import accountManagementNew.service.IUserService;
import accountManagementNew.utils.JWTUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author：lihonbin
 * @Version：1.0.0
 * @Date:2025/9/24
 * @Description: 认证控制器
 */
@RestController
@RequestMapping("/auth")
@Tag(name = "认证接口")
@AllArgsConstructor
public class AuthController {

    private final IUserService userService;

    /**
     * 登录
     * @param user  登录用户信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody UserDTO user){
        // 非空校验
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            return Result.error(ResultCodeEnum.FAIL, "用户名或密码不能为空");
        }
        UserVO userVO = userService.login(user);
        // 登录失败
        if (userVO == null) {
            return Result.error(ResultCodeEnum.UNAUTHORIZED, "用户名或密码错误");
        }
        // 登录成功,生成JWT token
        String token = JWTUtil.generateToken(userVO.getUsername());
        // 创建登录响应对象
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        loginVO.setUser(userVO);
        return Result.success("登录成功", loginVO);
    }
}
